package com.itheima.service;

import com.itheima.dao.ContactMapper;
import com.itheima.pojo.PageInfo;
import com.itheima.pojo.Student;
import com.itheima.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ContactService {
    public List<Student> findAll() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        List<Student> list = mapper.findAll();
        MybatisUtils.close(sqlSession);
        return list;
    }


    public List<Student> findByPage(int startIndex, int pageSize) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        List<Student> list = mapper.findByPage(startIndex, pageSize);
        MybatisUtils.close(sqlSession);
        return list;
    }

    public Boolean addStu(Student stu) {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        Student repeat = mapper.findByNumber(stu.getNumber());
        if (repeat == null) {
            mapper.addStu(stu);
            MybatisUtils.close(sqlSession);
            return true;
        } else {
            MybatisUtils.close(sqlSession);
            return false;
        }
    }

    public Boolean delete(String number) {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        int i = mapper.delete(number);
        return i > 0;
    }

    public Boolean update(Student stu) {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactMapper mapper = sqlSession.getMapper(ContactMapper.class);
        int i = mapper.update(stu);
        return i > 0;
    }
}
